import {PlusOutlined} from '@ant-design/icons';
import {ActionType, FooterToolbar, ProColumns, ProTable,} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message, Popconfirm} from 'antd';
import React, {useRef, useState} from 'react';
import CreateUpdateForm from '@/pages/Admin/InterfaceParam/components/CreateUpdateForm';
import {
  addInterfaceParamUsingPost,
  deleteInterfaceParamUsingPost,
  listInterfaceParamByPageUsingPost,
  updateInterfaceParamUsingPost,
} from '@/services/sutongapi-backend/interfaceParamController';

/**
 * 添加接口参数
 *
 * @param fields
 */
const handleAdd = async (fields: API.InterfaceInfo) => {
  const hide = message.loading('正在添加');
  try {
    await addInterfaceParamUsingPost({
      ...fields,
    } as API.InterfaceParamAddRequest);
    hide();
    message.success('添加成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '添加失败，请重试');
    return false;
  }
};

/**
 * 更新接口参数
 *
 * @param fields
 */
const handleUpdate = async (fields: API.InterfaceInfo) => {
  const hide = message.loading('正在修改');
  try {
    await updateInterfaceParamUsingPost({
      ...fields,
    } as API.InterfaceParamUpdateRequest);
    hide();
    message.success('修改成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '修改失败，请重试');
    return false;
  }
};

/**
 * 删除接口参数
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.InterfaceInfo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    // 性能问题
    for (let row of selectedRows) {
      await deleteInterfaceParamUsingPost({
        id: row.id ?? 0,
      });
    }
    hide();
    message.success('删除成功，将很快刷新');
    return true;
  } catch (error: any) {
    hide();
    message.error(error.message ? error.message : '删除失败，请重试');
    return false;
  }
};

export type TableProps = {
  interfaceInfoId?: number;
  type?: number;
  search?: boolean;
};
const InterfaceParamTable: React.FC<TableProps> = (props) => {
  const [modalOpen, handleModalOpen] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>('');
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  const actionRef = useRef<ActionType>();

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.InterfaceParam>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      tip: '主键',
    },
    {
      title: '所属接口ID',
      dataIndex: 'interfaceInfoId',
      initialValue: props.interfaceInfoId,
    },
    {
      title: '类型',
      dataIndex: 'type',
      initialValue: props.type,
      valueEnum: {
        0: {
          text: '请求参数',
          status: 'Default',
        },
        1: {
          text: '响应参数',
          status: 'Processing',
        },
        2: {
          text: '请求头参数',
          status: 'Success',
        },
        3: {
          text: '响应头参数',
          status: 'Error',
        },
      },
    },
    {
      title: '参数名称',
      dataIndex: 'name',
      valueType: 'text',
      ellipsis: true,
    },
    {
      title: '参数说明',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '参数字段类型',
      dataIndex: 'fieldType',
      valueType: 'text',
    },
    {
      title: '是否必填',
      dataIndex: 'required',
      valueEnum: {
        0: {
          text: '否',
          status: 'Error',
        },
        1: {
          text: '是',
          status: 'Success',
        },
      },
    },
    {
      title: '创建人',
      dataIndex: 'userId',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      ellipsis: true,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      ellipsis: true,
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '120px',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleModalOpen(true);
            setCurrentRow(record);
            setModalTitle('修改接口');
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="delete"
          title="删除接口"
          description="您确定要删除此接口吗？"
          onConfirm={async () => {
            const res = await handleRemove([record]);
            if (res) {
              actionRef.current?.reloadAndRest?.();
            }
          }}
        >
          <a style={{ color: 'red' }} key="delete">
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <>
      <ProTable<API.InterfaceParam, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        search={props.search ?? true ? { labelWidth: 120 } : false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
              setCurrentRow({});
              setModalTitle('新建接口');
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort) => {
          let queryParams: any = {
            ...params
          };
          if (props.interfaceInfoId != null) {
            queryParams.interfaceInfoId = props.interfaceInfoId;
          }
          if (props.type != null) {
            queryParams.type = props.type;
          }

          // 如果存在排序信息，对数据进行排序
          if (sort && Object.keys(sort).length) {
            const [[sortField, sortOrder]] = Object.entries(sort);
            queryParams.sortField = sortField;
            queryParams.sortOrder = sortOrder;
          }
          const res = await listInterfaceParamByPageUsingPost({
            ...queryParams,
          });

          return {
            data: res.data?.records || [],
            success: res.code === 0,
            total: res.data?.total || 0,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      <CreateUpdateForm
        interfaceInfoId={props.interfaceInfoId}
        type={props.type}
        title={modalTitle}
        open={modalOpen}
        onOpenChange={handleModalOpen}
        initialValues={currentRow}
        onFinish={async (value) => {
          let res = undefined;
          if (value.id) {
            res = await handleUpdate(value as API.InterfaceInfo);
          } else {
            res = await handleAdd(value as API.InterfaceInfo);
          }
          if (res) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />
    </>
  );
};
export default InterfaceParamTable;
